package com.ytjj.quartz.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.gexin.fastjson.JSON;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.EncryptUtil;
import com.ytjj.quartz.model.BatchInsertChannelStatisticDataRequest;
import com.ytjj.quartz.model.DataStatisticsRequest;
import com.ytjj.quartz.model.MobileVO;
import com.ytjj.quartz.service.ChannelStatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Value;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@RequestMapping("/channel")
@RestController
@Slf4j
@RefreshScope
public class ChannelStatisticsController {
    @Autowired
    private ChannelStatisticsService channelStatisticsService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Value("${santong.account:dh42425}")
    private String account;
    @Value("${santong.password:gXjNTv08}")
    private String password;

    // https://guobao.quanminyanxuan.cn/quartz/channel/sendSms
    @GetMapping("/sendSms")
    public CommonResult batchSendSms() {
        String filePath = "/mnt/qmyx/mobile.xlsx";
        File file=new File(filePath);
        if(!file.exists()){
            throw new ApiException("文件不存在!");
        }
        Sheet sheet = new Sheet(1, 0, MobileVO.class);
        AtomicInteger index = new AtomicInteger(1);
        try {
            List<Object> list = EasyExcelFactory.read(new BufferedInputStream(new FileInputStream(file)), sheet);
            if (CollectionUtils.isEmpty(list)) {
                return CommonResult.success("没有需要发送的手机号");
            }

            String message = "尊敬的会员，您好！由于业务变更，部分链接已失效；现查询订单、物流或咨询客服，请前往<XXXX优品2>公众号查询。给您造成不便，敬请谅解!";
            list.stream().forEach(item -> {
                MobileVO mobileVO = (MobileVO) item;

                String[] phones = {mobileVO.getMobile()};
//                String result = EncryptUtil.sendSanTong("http://www.dh3t.com/json/sms/Submit", account, password, phones, message);
//                log.info("===三通返回结果：{}，{}", mobileVO.getMobile(), result);
                index.getAndAdd(1);
            });
        } catch (FileNotFoundException e) {
            log.error("===文件找不到==={}", filePath);
        }
        return CommonResult.success(index);
    }

    @GetMapping("/batch/insert")
    public CommonResult batchInsert(
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startTimeLD = LocalDateTime.parse(startTime, df);
        LocalDateTime endTimeLD = LocalDateTime.parse(endTime, df);
        DataStatisticsRequest dataStatisticsRequest = DataStatisticsRequest.builder()
                .startTime(startTimeLD)
                .endTime(endTimeLD)
                .build();
        channelStatisticsService.getPlatformStatisticsList(dataStatisticsRequest);
        return CommonResult.success();
    }
    @PostMapping("/batch/insert-p")
    public CommonResult batchInsertP(@RequestBody String requestJson) {
        List<BatchInsertChannelStatisticDataRequest> list = JSON.parseArray(requestJson, BatchInsertChannelStatisticDataRequest.class);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        list.stream().forEach(s -> {
            LocalDateTime startTimeLD = LocalDateTime.parse(s.getStartTime(), df);
            LocalDateTime endTimeLD = LocalDateTime.parse(s.getEndTime(), df);
            DataStatisticsRequest dataStatisticsRequest = DataStatisticsRequest.builder()
                    .startTime(startTimeLD)
                    .endTime(endTimeLD)
                    .build();
            channelStatisticsService.getPlatformStatisticsList(dataStatisticsRequest);
        });
        return CommonResult.success();
    }

    /**
     * 补统计渠道分成数据
     * @param dateJson
     * @param channelUid 渠道所属用户ID
     * @param type 1，仅统计渠道分成，2统计渠道分成和总分成，3统计渠道分成、总分成和数据分成
     * @return
     */
    @PostMapping("/batch/channelUserHistoryInsert")
    public CommonResult channelUserHistoryInsert(@RequestBody String dateJson,@RequestParam(value = "coupon", required = true) BigDecimal coupon
            ,@RequestParam(value = "parentCoupon", required = true) BigDecimal parentCoupon
            ,@RequestParam(value = "dataCoupon", required = true) BigDecimal dataCoupon
            ,@RequestParam(value = "channelUid", required = true) Integer channelUid,@RequestParam(value = "type", required = true) Integer type) {
        //要统计的日期列表
        List<String> dateList=JSON.parseArray(dateJson,String.class);

        for(String daystr:dateList) {
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime startTimeLD = LocalDateTime.parse(daystr+" 00:00:00", df);
            LocalDateTime endTimeLD = LocalDateTime.parse(daystr+" 23:59:59", df);
            DataStatisticsRequest dataStatisticsRequest = DataStatisticsRequest.builder()
                    .startTime(startTimeLD)
                    .endTime(endTimeLD)
                    .build();
            channelStatisticsService.getChannelDataTempByChannelUid(startTimeLD,endTimeLD,"h5",channelUid,dataStatisticsRequest,coupon,parentCoupon,dataCoupon,type,70);
        }
        return CommonResult.success();
    }
}
